import '@/scss/reset.scss';
import '@/scss/common.scss';
import '@/css/font-awesome.min.css';

import './mutiDomain.scss';
import $ from 'jquery';
import 'layui-layer/layer';
import {DOMAIN_QUERY_URL, QUERY_TOKEN_URL} from '@/js/api';
/*
 *
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 * 
 */

const DomainReg = {
  $form: $('#domain-query-form'),
  $searchBtn: $('#js-domain-search'),
  $searchInput: $('#js-domain-input'),
  $resetBtn: $('#js-param-reset'),
  $expandBtn: $('#js-expand'),
  $expandPanel: $('#js-hidden-panel'),
  init: function(){
    this.bindEvents()
    
    // 已经存在domainConfig这个参数的话，那么立即执行查询
    if(typeof(domainConfig) !== 'undefined'){
      this.searchDomain(domainConfig)
    }
  },
  bindEvents: function(){
    const t = this;

    // 展开按钮
    t.$expandBtn.on('click', function(){
      let isExpand = t.$expandPanel.hasClass('expand');
      let text = isExpand ? '展开 <i class="fa fa-angle-down"></i>' : '收起 <i class="fa fa-angle-up"></i>';
      t.$expandPanel.toggleClass('expand');
      $(this).html(text);
    })

    // 查询按钮
    t.$searchBtn.on('click', function(){
      let n = $.trim(t.$searchInput.val()).replace(/\n/g,',').replace(/\s/g,'');
      let $suffixLabels = $('input[name="suffix"]:checked');
      if(n && $suffixLabels.length > 0){
        if(n.indexOf('.') > 0){
          layer.alert('直接输入域名如 <strong>yunfv</strong><br>不必输入 <strong>www.</strong> 和 <strong>域名后缀</strong>')
        }else{
          let suffixArr = [];
          let suffixString = '';
          $suffixLabels.each(function(){
            suffixArr.push($(this).val())
          })
          suffixString = suffixArr.join(',');
          let parameter = {
            name: n,
            suffix: suffixString
          }
          t.formSubmit(parameter)
        }
      }else{
        layer.alert('请输入域名 和 勾选后缀')
      }
    })

    // 重置查询条件
    t.$resetBtn.on('click', function(){
      t.$searchInput.val('')
      t.$form.find('input[name="suffix"]:checked').prop('checked', '');
      t.$form.find('input[name="suffix"][data-reset="1"]').prop('checked', 'checked');
    })

    // 批量注册按钮
    $('#regBtn').on('click', function(){
      let $selectedLabel = $("#registableList").find('input[name="domainsset"]:checked');
      if(freeid!=""){
        layer.alert("赠品域名只能选择单个域名注册")
		    return false;
      }
      if($selectedLabel.length > 0){
        let domain = [];
        for(let item of $selectedLabel){
          domain.push($(item).val())
        }
        domain = domain.join(',')
        // 至此已经转成 yunfv.com,baidu.com 这样的字符串
        $('#batch-reg-form').find('input[name="domain"]').val(domain);
        $('#batch-reg-form').find('input[name="ajaxFree"]').val(freeid);
        $('#batch-reg-form').submit();
      }else{
        layer.alert('请选择您要注册的域名')
      }
    })
  },
  // 提交查询
  formSubmit: function(n){
    this.$form.find('input[name="searchedDomainName"]').val(n.name);
    this.$form.find('input[name="suffix"]').val(n.suffix);
    this.$form.submit();
  },
  /*
   * 参数是 domain = {name: "yunfv,baidu,west",suffix: ".com,.cn,.top"} 这样的形式
   * 目的是返回 {"domain": ["yunfv", "baidu", "west"], "suffix": ".com,.cn,.top"} 这样的参数
   */ 
  toJson: function(domain){

    let suffixStr =  '"suffix": "' + domain.suffix + '",';
    let nameArr = domain.name.split(',');
    let nameStr = '"domain": [' + computed(nameArr) + ']';
    let domainJson = "{" + suffixStr + nameStr + "}";

    return $.parseJSON(domainJson);

    function computed(c){
      let i = 0;
      let str = '';
      while(c[i]){
        i == 0 ? str += '"' + c[0] + '"' : str += ',"' + c[i] + '"';
        i++
      }
      return str
    }
  },

  // 查询域名
  searchDomain: function(param){
    let parameter = this.toJson(param);
    // 显示加载中
    $('#load').addClass('show');

    $.get(QUERY_TOKEN_URL + '?r=' + Math.random())
      .then((token)=>{
        return $.ajax({
          url: DOMAIN_QUERY_URL,
          type: "POST",
          dataType: "json",
          data: "searchedDomainName=" + escape($.trim(parameter.domain)) + "&suffix=" + escape($.trim(parameter.suffix)) + "&module=domainsearch&t=" + token
        })
      }
    ).done((data)=>{
      if(data.code == "200"){
        const t = this;
        // 关闭加载中
        $('#load').removeClass('show');
        // 清除上次查询的结果
        $("#result-table").find('ul').empty()
        // 可注册域名
        let registable = data.datainfo.ok;
        // 已注册域名
        let registed = data.datainfo.no;
         // 溢价域名
        let tradable = data.datainfo.premium;
        // 查询失败域名
        let failed = data.datainfo.err;
        t.buildRegistableList(registable)
        t.buildRegistedList(registed)
        t.buildTradableList(tradable)
        t.buildFailedList(failed)
      }
    }).fail(()=>{
      $('#load').removeClass('show');
      layer.alert('查询失败，请重试')
    })
  },
  // 查询后显示可注册域名
  buildRegistableList: function(data){
    let list = "";
    if(data.length > 0){
      for(let item of data){
        list += 
        `<li>
          <label class="checkbox">
            <input name="domainsset" type="checkbox" value="${item.domain}" checked> ${item.domain}
          </label>
          <span>&yen; <em>${item.Price}</em> 元/首年</span>
        </li>`
      }
      $('#registableList').append(list)
    }
  },
  // 查询后显示已注册域名
  buildRegistedList: function(data){
    let list = "";
    if(data.length > 0){
      for(let item of data){
        let dm = escape(item.domain);
        list += 
        `<li>
          ${item.domain}
          <span class="addon"><a href="view.asp?domain=${dm}" target="_blank">查询信息</a></span>
        </li>`
      }
      $('#registedList').append(list)
    }
  },
  // 查询后显示溢价域名
  buildTradableList: function(data){
    let list = "";
    if(data.length > 0){
      for(let item of data){
        let dm = escape(item.domain);
        list += 
        `<li>
          ${item.domain}
          <span class="addon"><a href="view.asp?domain=${dm}" target="_blank">查询信息</a></span>
          <span>&yen; <em>${item.Price}</em></span>
        </li>`
      }
      $('#tradableList').append(list)
    }
  },
  // 查询后显示查询失败域名
  buildFailedList: function(data){
    let list = "";
    if(data.length > 0){
      for(let item of data){
        let dm = escape(item.domain);
        list += 
        `<li>
          ${item.domain}
          <span class="addon"><a href="view.asp?domain=${dm}" target="_blank">查询信息</a></span>
        </li>`
      }
      $('#failedList').append(list)
    }  
  }
}

$(document).ready(function(){
  DomainReg.init(); 
})